<template>
  <div class='page white-stage reassignClients'>
    <top-filter
    ref="topFilter"
    :activeItem="filterActiveItem"
    :filterOptions="filterOptions" @load-more="loadFilter" :ismemberIsShow="false" :customPropertyWX="false"
    @change-filter="changeFilterValue" @item-selected="topFilterItemSelected"></top-filter>

    <search-input v-if="isShowSearch" @search-change="searchChange"></search-input>
    <div class="pagination-fixer">
      <h6 class="target-title"><template>{{ teamName }}</template></h6>
     <el-pagination class="filter-item mgl"
      ref="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[queryData.page_size]"
      :page-size="queryData.page_size"
      layout="sizes, prev, pager, next, jumper, total"
      :total="this.total">
      </el-pagination>
    </div>
    <div class="pdt scroll-container grey"
         ref="my_scroller"
         :style="'padding-top: 92px; height:' + this.scrollerHeight + 'px'" @scroll="scroll">
      <div class="clients-list">
          <div class="rela-tip-main">
            <div class="rela-result-tip top-list-counter">总计{{ total }}条记录</div>
          </div>

          <checker v-if="batchCheck" type="checkbox" v-model="checkedClients" selected-item-class="checker-item-active">
            <checker-item class="block-item" :value="toString(client.id)" v-for="(client, index) in clientList" :key="index">
              <reassign-custom-item
                      :isLinkToFollowRecord="true"
                      @on-click="onItemClick"
                      :key="index" :value="client"
                      :suser="client.user_name"
                      :custom_type="custom_type"
                      :batchCheck="batchCheck"
                      propPosition="bodyTop"
                      :showProp="false"
                      :showMobile="true">
                <div class="pull-left" v-if="batchCheck"  slot="checkerItem" >
                  <div class="batch-check-item">
                    <i class="selected-ico"></i>
                  </div>
                </div>
              </reassign-custom-item>
            </checker-item>
          </checker>

          <reassign-custom-item
                  v-for="(client, index) in clientList"
                  v-else :isLinkToFollowRecord="true"
                  :key="index"
                  :showProp="false"
                  propPosition="bodyTop"
                  :value="client" :custom_type="custom_type" :showMobile="true">
          </reassign-custom-item>

          <div class="center-content-block" style="margin-top: 10px;" v-if="loading === true">
            <mt-spinner type="snake"></mt-spinner>
          </div>
      </div>
    </div>
    <button class="fixed-bt-btn fixed-btr0-btn" v-if="!batchCheck && !show" @click="batchCheck=true">批量分配</button>
    <button class="fixed-bt-btn fixed-btr2-btn" v-if="batchCheck" @click="selectAll">全选</button>
    <button class="fixed-bt-btn fixed-btr1-btn" v-if="batchCheck" @click="batchCheck=false">取消</button>
    <button class="fixed-bt-btn fixed-btr0-btn" v-if="batchCheck" @click="distributeTrigger">分配</button>
    <crm-cover v-if="isShowCover" :hideCoverOnClick="true"></crm-cover>
    <crm-tabbar ref="tabbar" :activeItem='activeItem' v-if="activated"></crm-tabbar>

    <distribute-client
    :isShow="show"
    @on-cancel="show=false"
    :deliverTeamOpts="deliverTeamOpts"
    @on-confirm="memberSelect" />


    <x-dialog v-model="this.$store.state.app.dialogShow" >
      <div class="dialog-message">
        {{ this.$store.state.app.dialogMessage }}
      </div>
      <span class="vux-close" @click="hideDialog">知道了</span>
    </x-dialog>
    <confirm v-model="showDistributeConfirm"
        title="温馨提示"
        @on-confirm="onDistributeConfirm">
      <p style="text-align:center;">你确定要分配客户给此成员吗?</p>
    </confirm>
  </div>

</template>
<script>
    // import Vue from 'vue'
  import { getCustomSource } from '../lib/client'
  import { getSourceOptions } from '../lib/options/source'
  import { getChannelOptions } from '../lib/options/channel'
  import crmTabbar from '../components/crm-tabbar'
  import crmCover from '../components/crm-cover'
  import topFilter from '../components/top-filter'
  import teamMemberItem from '../components/team-member-item'
  import clientseasItem from '../components/clientseas-item'
  import DistributeClient from '../components/distribute-client'
  import reassignCustomItem from '../components/reassign-custom-item'

  // import Scroller from 'vue-scroller'

  // import {Popup, XDialog} from 'vux'
  // import XInput from 'vux/src/components/x-input'
  // import Group from 'vux/src/components/group'
  import Popup from 'vux/src/components/popup'
  import XDialog from 'vux/src/components/x-dialog'
  import { Checker, CheckerItem } from 'vux/src/components/checker'
  import store from '../store'
  import { mapActions, mapState } from 'vuex'

  // 按需引入加载mint-ui更多插件
  import 'mint-ui/lib/loadmore/style.css'
  import 'mint-ui/lib/spinner/style.css'
  import 'mint-ui/lib/infinite-scroll/style.css'
  import { Loadmore, Spinner } from 'mint-ui'
  import  { Pagination } from 'element-ui'

  import SearchInput from '../components/SearchInput'
  import {loadTeamSettings, loadMemberSettings, loadFilterFunc} from '../lib/filter'
  import {showDialog, hideDialog} from '../lib/dialog'
  import Q from 'q'
  import Confirm from 'vux/src/components/confirm'
  var zepto = require('npm-zepto')
  import  { mapField } from '../lib/backend'
  import defaultOptions from '../lib/options/defaultOptions'

  export default {
    data () {
      return {
        activated: true,
        total: 0,
        scrollerHeight: '',
        scrollerTop: '',
        isMore: false,
        loading: false,
        hasMoreData: true,
        batchCheck: false,
        memberHasMoreData: true,
        teamLoading: false,
        showDistributeConfirm: false,
        activeItem: '',
        page_size: 15,
        page_index: 1,
        team_page_index: 1,
        custom_type: 0,
        is_member:0,
        isShowSearch: false,
        show: false,
        filterActiveItem: {},
        keyword: '',
        noDataText: '',
        checkedClients: '',
        tnoDataText: '',
        deliverTeamOpts: [],
        init: false,
        cleanClientList: {},
        originNoDataText: '暂无数据',
        clientList: [],
        teamFilterOptions: [],
        teamsMembers: [],
        selectedClientId: null,
        filterData: {},
        currentPage: 1,
        filterOptions: [],
        queryData: {
          page_index: 1,
          page_size: 20
        },
        teamName: '',
        homeTop: 0
      }
    },
    components: {
      crmTabbar,
      crmCover,
      topFilter,
      clientseasItem,
      Popup,
      teamMemberItem,
      // Scroller,
      SearchInput,
      Checker,
      CheckerItem,
      XDialog,
      Confirm,
      DistributeClient,
      [Loadmore.name]: Loadmore,
      [Spinner.name]: Spinner,
      [Pagination.name]: Pagination,
      reassignCustomItem
    },
    activated () {
      if (this.position) {
        this.$refs.my_scroller.scrollTop = this.position.top
      }
      let scroller = this.$refs.my_scroller

      zepto(scroller).unbind('scroll.' + this.custom_type)
        .on('scroll.' + this.custom_type, () => {
          let scrollTop = this.$refs.my_scroller.scrollTop
          this.position = {top: scrollTop}
        })
       this.activated = true
     },
    deactivated () {
     this.activated = false
      this.position = {
        // left: 200,
        top: this.homeTop
      }
     console.log('this.position', this.position)
    },
    watch: {
      clientList () {
        this.cleanClientList = {}
        this.clientList.forEach((elem, index) => {
          this.cleanClientList[elem.id] = elem
        })
      },
      checkedClients (checkedClients) {
        console.debug('checkedClients', JSON.stringify(checkedClients))
        this.selectedClientId = checkedClients
      },
      batchCheck (val) {
        if (val === false) {
          this.checkedClients = []
        }
      },
      show (val) {
        if (val === false) {
          this.selectedClientId = ''
        }
      },
      init (value) {
        if (value === true) {
          console.log('******')
          this.$nextTick(() => {
            this.getCustoms()
          })
        }
      }
    },
    methods: {
      scroll(event) {
        this.homeTop = event.target.scrollTop
        console.log('scroll', event.target.scrollTop)
      },
      handleSizeChange () {
      },
      handleCurrentChange (val) {
        this.queryData = {
          ...this.queryData,
          page_index: val
        }
        this.currentPage = val
        console.log('val', val, this.currentPage)
        this.getCustoms()
      },
      initPageFilters (pageData) {
        console.log('initPageFilters')
        const totalPage = Math.ceil(pageData['total'] / this.queryData.page_size)
        const filters = []
        for (let i = 1; i <= totalPage; i++) {
          filters.push({
            value: i,
            text: i
          })
        }
        this.filters = filters
      },
      distributeTrigger () {
        this.show = true
        this.initDistributeTeamOpts()
      },
      initDistributeTeamOpts () {
        const data = this.$refs.topFilter.getData()
        const myTeamList = this.loginUser.my_team_list
        const myTeamManangeList = this.loginUser.teams
        let deliverTeamOpts = []

        let is_manage = false
        if (data.team_id && ! this.loginUser.is_manager) {
          for (const teamId in myTeamManangeList) {
            deliverTeamOpts.push({
              key: myTeamManangeList[teamId].team_id,
              value: myTeamManangeList[teamId].team_name
            })
            if (data.team_id == myTeamManangeList[teamId].team_id) {
              is_manage = true
            }
          }
          if (! is_manage) {
            this.show = false;
            this.batchCheck = false
            showDialog('你不是当前团队管理员');
            return false
          }
        // if (data.team_id) {
        //  deliverTeamOpts = [
        //    {
        //      key: data.team_id,
        //      value: myTeamList[data.team_id]
        //    }
        //  ]
        } else {
          for (const teamId in myTeamList) {
            deliverTeamOpts.push({
              key: teamId,
              value: myTeamList[teamId]
            })
          }
        }
        this.deliverTeamOpts = deliverTeamOpts
      },
      selectAll () {
        const list = []
        this.clientList.forEach((client, index) => {
          list.push(client.id + '')
        })
        this.checkedClients = list
      },
      caculateScroller () {
        console.log(this.$refs['topFilter'])
        const winHeight = window.innerHeight
        const filterHeight = this.$refs['topFilter'].$el.offsetHeight
        const tabbarHeight = this.$refs['tabbar'].$el.offsetHeight
        this.scrollerTop = filterHeight
        this.scrollerHeight = winHeight - filterHeight - tabbarHeight
      },
      showConfirmDialog (member) {
        this.selectedMember = member
        this.showDistributeConfirm = true
      },
      onDistributeConfirm () {
        this.memberSelect(this.selectedMember)
      },
      toString (id) {
        return id + ''
      },
      loadTeamRelative () {
        loadTeamSettings({}, {checked: true}).then((options) => {
          if (options === false) return this.filterTeamIndex = 0
          this.filterOptions[1]['options'][2] = options[1]
        }).then(loadMemberSettings).then((options) => {
          if (false === options) return this.filterMemberIndex = 0
          this.filterOptions[1]['options'][1] = options[1]
          this.init = true
          this.filterData = this.$refs.topFilter.getData()
        }).catch(() => {
          this.init = true
        })
      },

      refresh (iscroll) {
        this.getCustoms();
      },
      loadFilter :loadFilterFunc,
      log () {
        console.log('ee');
      },

      load (iscroll) {
        if (this.init) {
          this.getCustoms()
        }
      },

      topFilterItemSelected(item, index) {
        console.log('topFilterItemSelected')

        if (typeof item.name !== 'undefined' && item.name === 'search') {
          this.isShowSearch  = !this.isShowSearch //搜索栏打开
        } else {
          this.isShowSearch = false//打开的是筛选栏
        }

        if(this.isShowSearch === false && this.keyword) {
          if(this.isShowSearch === false) {
            this.keyword = ''
            this.emptyCustoms()
            this.getCustoms()
          }
        }

      },

      isSameObj (obj1, obj2) {
        return JSON.stringify(obj1) === JSON.stringify(obj2)
      },
      initBatchCheck () {
        let that = this
        let items = [
          {
            'id': 'batchCheck', // 字符串
            'text': '批量分配'
          }
        ]
        const dd = window['dd']
        // dd.biz.navigation.setMenu({
        //   backgroundColor: '#FFFFFF',
        //   textColor: '#0089cd',
        //   items: items,
        //   onSuccess: function (data) {
        //     // this.checkedClients
        //     if (that.batchCheck !== true) {
        //       that.batchCheck = true
        //     }
        //   },
        //   onFail: function (err) { }
        // })
      },

      emptyCustoms () {
        this.clientList = []
        this.clientIDs = []
        this.page_index = 1
        this.hasMoreData = true
        this.loading = false
      },

      searchChange (value) {
        if (!value) return
        if (typeof this.sid !== 'undefined') {
          clearTimeout(this.sid)
        }

        this.sid = setTimeout(() => {
          if(!this.originClientList) {
            this.originClientList = this.clientList
          }
          this.emptyCustoms()
          this.keyword = value
          this.getCustoms()
        }, 1000)
      },

      refreshMember (iscroll) {
        this.loadMembers();
        console.log('refreshMember')
        // Refresh current data
      },

      logMember () {
        console.log('logMember');
      },

      loadMember (iscroll) {
        console.log('loadMember')
        this.loadMembers();
        // Load new data
      },

      hidePopup (status) {
        showDialog('你取消了分配！');
        this.show = false;
        console.log('hidePopup')
      },

      hideDialog () {
        hideDialog()
        this.emptyCustoms()
        this.getCustoms()
      },

      test () {
        console.log('test')
      },

      onItemClick(clientID){
        // this.teamsMembers = [];
        this.loadMembers();
        this.initDistributeTeamOpts()
        this.show = true;
        this.selectedClientId = clientID;
        console.log('clientID: ', clientID);
      },

      memberSelect(member) {
        console.log('memberSelect: ', member.suid);
        if (!this.selectedClientId) {
          showDialog('您必须选择至少一个客户!')
          return
        }

        let info = {
          target_suid: member.suid,
          target_team_id: member.team_id,
          custom_id: this.selectedClientId,
          distribute_type: 'TP#',
          opt_type: 'TPT'
        };

        let that = this;
        this.$vux.loading.show({text:'loading'})

        store.dispatch('distribute', info).then((response) => {
          if(response.data.errcode === 0) {
            showDialog('您将客户分配给成员：' + member.name);
            that.show = false
            // that.$router.back();
            this.batchCheck = false
          } else {
            showDialog(response.data.errmsg)
            console.log(JSON.stringify(response.data));
          }
          this.$vux.loading.hide()
        }).catch((error) => {
          showDialog('系统出错!')
          this.$vux.loading.hide()
          console.log(error)
        });
      },

      getCustoms (data) {
        let defaultData = this.$refs.topFilter.getData()
        console.log(defaultData, 'defaultData')
        let that = this

        if (this.loading === true || this.hasMoreData === false) return
        this.loading = true

        defaultData['custom_type'] = this.custom_type;
//        defaultData['page_size'] = this.page_size;
//        defaultData['page_index'] = this.page_index;
        defaultData['is_member'] = this.is_member
        defaultData['order_by'] = 0;
        defaultData['type'] = 'distribute'
        if (this.keyword) defaultData['keyword'] = this.keyword
        data = Object.assign(this.queryData, defaultData, data);
        console.log(JSON.stringify(data), '****data')

        store.dispatch('getCustoms', data).then((response) => {
          this.loading = false

          let resData = response.data
          if (resData.errcode === 0) {
            let freshData = []
            that.page_index ++

            const totalPage = Math.ceil(parseInt(resData.results.total) / parseInt(this.page_size))
//            this.hasMoreData = this.page_index < totalPage

            if (this.total != resData.results.total) this.initPageFilters(resData.results)
            this.total = resData.results.total
            this.teamName = resData.results.team_name
            if (typeof this.clientIDs === 'undefined') this.clientIDs = []

            that.clientList = resData.results.data;

            // setTimeout(() => {
            //   if (that.$refs.my_scroller) {
            //     that.$refs.my_scroller.finishInfinite(true);
            //     that.$refs.my_scroller.finishPullToRefresh();
            //     setTimeout(() => {
            //       that.$refs.my_scroller.resize();
            //     })
            //   }
            // }, 1500)

            if(that.clientList.length) {
              that.noDataText = '';
            }

          } else {
            console.log('系统服务异常！请联系管理员!', JSON.stringify(response.data));
          }
        }).catch((error) => {
          this.loading = false
          this.hasMoreData = true
          console.log(error)
        })
      },
      loadMembers (data) {
        return Q.Promise((resolve, error) => {
          let that = this
          let params = {
            page_index: this.team_page_index,
            page_size: this.page_size,
            is_own: 1,
            source: 'webapp'
          }

          if (this.teamLoading === true || this.memberHasMoreData === false) return
          this.teamLoading = true

          params = Object.assign(params, data)
          store.dispatch('getTeams', params).then((response) => {
            this.teamLoading = false
            const totalPage = Math.ceil(parseInt(response.data.results.total) / parseInt(this.page_size))
            this.memberHasMoreData = this.team_page_index < totalPage

            setTimeout(() => {
              if (typeof response.data.results.teams !== 'undefined') {
                let teams = response.data.results.teams;
                that.filterUserFromTeam(teams)
                resolve(true)
              } else {
                console.log(that.teamsMembers)
              }
              this.endTeamLoading()
              that.team_page_index++

            }, 800)

          }).catch((e) => {
            console.log(e)
            this.teamLoading = false
            this.memberHasMoreData = false
            this.endTeamLoading()
          })
        })

      },
      //从接口中筛选出团队信息
      filterUserFromTeam(teams) {
        let temps = [];

        if(!this.existTeamsIDs) this.existTeamsIDs = []

        teams.forEach((team, index) => {
          let isSelfTeam = false

          // team.team_managers.forEach((member, mindex) => {
          //   if(member.suid === this.loginUser.id) {
          //     isSelfTeam  = true
          //   }
          // });

          if(team.id === this.loginUser.teams[0].team_id) isSelfTeam = true

          // if(true === isSelfTeam) {
            if (team.team_managers) {
              team.team_managers.forEach((member, mindex) => {
                let gid = member.suid+'_'+team.id
                if(this.existTeamsIDs.indexOf(gid) === -1)  {
                  member.team_name = team.team_name;
                  temps.push(member);
                  // console.log(this.existTeamsIDs)
                  this.existTeamsIDs.push(gid)
                }
              });
            }

            if (team.team_members) {
              team.team_members.forEach((member, mindex) => {
                let gid = member.suid+'_'+team.id
                if(this.existTeamsIDs.indexOf(gid) === -1)  {
                  member.team_name = team.team_name;
                  temps.push(member);
                  // console.log(this.existTeamsIDs)
                  this.existTeamsIDs.push(gid)
                }
              });
            }

          // }
        });
        this.teamsMembers = this.teamsMembers.concat(temps);
      },
      endTeamLoading() {
        let that = this
        setTimeout(() =>{
          if (that.$refs.team_scroller) {
            // that.$refs.team_scroller.finishInfinite(true);
            // that.$refs.team_scroller.finishPullToRefresh();
            if (that.teamsMembers.length > 0) {
              that.tnoDataText = ''
            }
            // setTimeout(() => {
            //   if(this.$refs.team_scroller) {
            //     this.$refs.team_scroller.resize()
            //   }
            // },200)
          }
        }, 1500)
      },

      //筛选器
      changeFilterValue(filterOptions) {
        this.filterData = this.$refs.topFilter.getData()
        this.emptyCustoms();
        this.getCustoms();
//        this.initDistributeTeamOpts()
      },

      handlePopup(status){

        this.team_page_index = 1;
        if(status === 'show') {
          // setTimeout(() => {
          //   if(this.$refs.team_scroller) {
          //     this.$refs.team_scroller.resize()
          //   }
          // },200)
        } else {

        }
      },
      ...mapActions({
        'updateSourceFilter': 'updateSourceFilter',
        'updateChannelFilter': 'updateChannelFilter'
      })
    },
    computed: {
      ...mapState({
        isShowCover: state => state.app.isShowCover,
        defFilterOptions: state => state.app.filterOptions,
        loginUser: state => state.app.user,
        isUpdateSourceFilter: state => state.app.updateSourceFilter,
        isUpdateChannelFilter: state => state.app.updateChannelFilter
      })
    },
    beforeMount () {
      this.filterOptions = defaultOptions
    },
    mounted () {
      this.caculateScroller()

      if (this.loginUser.is_team_manager) {
        this.loadMembers().then((status) => {
          if (status === true) {
            this.initBatchCheck()
            this.team_page_index ++
            // this.batchCheck = true
          }
        })
      }

      if (!this.isUpdateSourceFilter) {
        getCustomSource(store).then((customSources) => {
          let sourceOptions = getSourceOptions(customSources)
          this.filterOptions[1].options.push(sourceOptions)
        })
        this.updateSourceFilter()
      }

      if (!this.isUpdateChannelFilter) {
        getChannelOptions().then((channelOptions) => {
          this.filterOptions[1].options.push(channelOptions)
        })
        this.updateChannelFilter()
      }

      let query = this.$route.query;
      this.custom_type = query.custom_type;
      this.activeItem = query.activeItem;
      this.is_member = query.is_member

      console.debug('custom_type', this.custom_type);
      console.debug('activeItem', this.activeItem);
      this.noDataText = this.originNoDataText;
      this.tnoDataText = this.originNoDataText;

      // this.filterOptions = this.gbfilterOptions;
      this.teamFilterOptions = this.gbfilterOptions;

      this.loadMembers()
      this.loadTeamRelative()
      this.callJsApi('biz.navigation.setTitle',{title:query.title});

      // this.getCustoms();
      // this.loadMembers();
    }


    }
</script>
<style lang="less">

  @import "../less/base";
  .target-title {
    text-align: center;
  }

  .clients-list{
    // margin-top: 20px;
    background-color: #EFEFF4;
    min-height: 100%;
    // padding-top: 10px;
  }

  .reassignClients {
    .pdscroll {
      background-color: #EFEFEF;
    }

    .scroll-container{
      padding-top: 18px;
      background-color: #EFEFF4;
    }

    .clientseas-item .client-desc {
      margin-bottom: 0;
    }

  }


  .grey.container.pdt{
    // padding-top: 18px;
  }
</style>
